'''# Third_party'''
from openpyxl import load_workbook
from openpyxl.styles import *

'''# built_in'''
import re
import os 

'''# custom'''
from dataRead.result.result_Report import Result
from dataRead.result.case_Step_Write import fieldWrite
from dataRead.auxiliary.run_Sheet_Row import RunSheetRow
from utils.public_Script import isLogicMethodClass
from utils.log.trusteeship import trusteeship


class TestCase:

    def __repr__(self) -> str:
        return "用例步骤文件操作控制类"

    def __init__(self) -> None:
        self.result_Object = Result()
        self.steps_Object = RunSheetRow()
        self.logicFunction_Object = isLogicMethodClass()

        self.casesData = []  # 用例数据列表
        self.summary = {'total': 0, 'implement': 0, 'passNum': 0, 'abnormalNum': 0, 'failNum': 0}  # 用例汇总数据
    
    def testCase(self, caseStepsFile_Path, caseNodeFile_Paht, resultFile_Paht) -> None:
        """
         参数：
            @param caseStepsFile_Path : 用例步骤文件[Excel]文件路径
            @param aseNodeFile_Paht : 用例节点文件[CaseStep.yaml]
            @param resultFile_Paht : 测试结果汇总文件路径
        """
        WB_Object = load_workbook(caseStepsFile_Path)
        self.summary['total'] = len(WB_Object.sheetnames)  # 用例总数
        elementExpression = self.logicFunction_Object.raw_YamlTxt(caseNodeFile_Paht) 

        for sheetName in WB_Object.sheetnames[:]:
            WS_Object = WB_Object[sheetName]
            WS_rowsMax = WS_Object.max_row
            WS_columnMax = WS_Object.max_column

            caseImplement = ''  # 用例执行结果
            acceptResult = []  # 断言结果暂存数组
            self.summary['implement'] += 1  # 执行用例数量+1

            # 调用封装函数进行测试文档准备工作，生成对应主题测试结果单元格
            caseName = WS_Object.cell(row=2, column=1).value; trusteeship.info(f'\n用例名：{caseName}------')
            writeColumn = fieldWrite(WS_Object, WS_columnMax, WS_rowsMax)

            # 单条用例步骤操作 [优先级 异常 > Fail > Pass]
            executeResult = self.steps_Object(WB_Object, WS_Object, WS_rowsMax, elementExpression, writeColumn, caseStepsFile_Path, acceptResult)
            if executeResult['abnormalJudgment'] == True:
                caseImplement = '异常'; self.summary['abnormalNum'] += 1
                trusteeship.debug("Use case execution result record: ---------- 异常")
            elif False in executeResult['acceptResult']:
                caseImplement = 'Fail'; self.summary['failNum'] += 1
                trusteeship.debug("Use case execution result record: ---------- Fail")
            else:
                caseImplement = 'Pass'; self.summary['passNum'] += 1
                trusteeship.debug("Use case execution result record: ---------- Pass")
            
            # 用例信息暂存 [caseName用例名称 || caseImplement用例执行结果 || executeResult['caseError']用例错误信息]
            self.casesData.append([caseName, caseImplement, executeResult['caseError']])

        # 汇总测试结果
        self.result_Object.resultHandle(resultFile_Paht, os.path.basename(caseStepsFile_Path), self.summary, self.casesData)
        return self.summary
    
    def __console_log(self, CASE_NAME, RETRY_RESULT, ERROR_REASON):
        """
         参数：
            @param CASE_NAME : 用例名称
            @param RETRY_RESULT : 用例执行结果
            @param ERROR_REASON : 用例异常错误原因
        """
        CASE_NAME = re.search('\w+(\()?(\d+)?(\))?\d+', CASE_NAME).group()  # 用例编号筛选
        log_Information = f'''
        ------------------------------------------\n
            用例编号：{CASE_NAME}\n
            第二次执行结果：{RETRY_RESULT}\n
            异常原因：{ERROR_REASON}\n
        '''
        self.logicFunction_Object.raw_YamlTxt(self.retry_Log_Path, 'a', log_Information)